package com.gskj.eduorder.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gskj.commonutils.JwtUtils;
import com.gskj.commonutils.ResultJson;
import com.gskj.eduorder.entity.Order;
import com.gskj.eduorder.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.sound.midi.Soundbank;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author Connor
 * @since 2020-08-17
 */
@RestController
@RequestMapping("/eduorder/order")
@CrossOrigin
public class OrderController {

    @Autowired
    private IOrderService orderService;


    /**
     * 1. 生成订单信息
     *
     * @param courseId
     * @return
     */
    @PostMapping("/create/order/{courseId}")
    public ResultJson saveOrder(@PathVariable("courseId") String courseId, HttpServletRequest request) {
        // 1. 用过jwtUtils 将 request中携带的token 解析得到对应的 会员id
        String memberId = JwtUtils.getMemberIdByJwtToken(request);

        // 2. 创建  订单信息,并返回订单号
        String orderId = orderService.createOrder(courseId, memberId);

        // 3. 将结果返回前台
        return ResultJson.success().data("orderNo", orderId);
    }

    /***
     *  2. 根据 订单号 查询对应的 订单信息
     * @param orderNo
     * @return
     */
    @GetMapping("/get/orderinfo/{orderNo}")
    public ResultJson getOrderInfoById(@PathVariable("orderNo") String orderNo) {


        // 1. 创建 查询 条件
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        // 根据 表字段 order_no
        wrapper.eq("order_no", orderNo);


        // 2. 调用service
        Order one = orderService.getOne(wrapper);
        // 3. 返回 前台
        return ResultJson.success().data("order", one);
    }


    /***
     * 根据 课程id、会员id 查询当前课程是否已购买。
     * @param memberId
     * @param courseId
     * @return
     */
    @GetMapping("/isbuy/course/{mid}/{cid}")
    public Boolean checkStatsByMidAndOid(
            @PathVariable("mid") String memberId,
            @PathVariable("cid") String courseId) {
        System.out.println("order  " + memberId);
        System.out.println("order  " + courseId);

        // 1. 封装查询条件
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("member_id", memberId);
        wrapper.eq("course_id", courseId);
        wrapper.eq("status", 1);

        // 只查询返回数据
        int count = orderService.count(wrapper);
        // 判断是否支付
        if (count > 0) {
            return true;
        }
        return false;
    }

}

